using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using SvgToFontConverter.Models;
using SvgToFontConverter.Services;
using MessageBox = System.Windows.MessageBox;

namespace SvgToFontConverter
{
    /// <summary>
    /// 引擎配置窗口
    /// </summary>
    public partial class EngineConfigWindow : Window
    {
        private readonly EngineConfigService _configService;
        private EngineConfig _currentConfig;
        
        public EngineConfigWindow()
        {
            InitializeComponent();
            _configService = new EngineConfigService();
            LoadConfiguration();
        }
        
        /// <summary>
        /// 加载配置
        /// </summary>
        private void LoadConfiguration()
        {
            _currentConfig = _configService.LoadConfig();
            
            // 如果配置为null，创建默认配置
            if (_currentConfig == null)
            {
                _currentConfig = _configService.CreateDefaultConfig();
            }
            
            // 设置引擎选择
            if (_currentConfig.SelectedEngine == EngineType.FontForge)
            {
                rbFontForge.IsChecked = true;
            }
            else if (_currentConfig.SelectedEngine == EngineType.FontelloCli)
            {
                rbFontelloCli.IsChecked = true;
            }
            else if (_currentConfig.SelectedEngine == EngineType.Svg2Ttf)
            {
                rbSvg2Ttf.IsChecked = true;
            }
            
            // 加载FontForge配置
            txtFontForgePath.Text = _currentConfig.FontForge.InstallPath;
            
            // 加载Fontello CLI配置
            txtNodeJsPath.Text = _currentConfig.FontelloCli.NodeJsPath;
            txtFontelloCliPath.Text = _currentConfig.FontelloCli.FontelloCliPath;
            txtServerUrl.Text = _currentConfig.FontelloCli.ServerUrl;
            
            // 加载SVG2TTF配置
            txtSvg2TtfNodeJsPath.Text = _currentConfig.Svg2Ttf.NodeJsPath;
            
            // 更新UI状态
            UpdateEngineVisibility();
            UpdateFontForgeStatus();
            UpdateFontelloCliStatus();
            UpdateSvg2TtfStatus();
        }
        
        /// <summary>
        /// 引擎选择改变事件
        /// </summary>
        private void EngineSelection_Changed(object sender, RoutedEventArgs e)
        {
            // 添加null检查保护
            if (_currentConfig == null)
                return;
                
            if (rbFontForge.IsChecked == true)
            {
                _currentConfig.SelectedEngine = EngineType.FontForge;
            }
            else if (rbFontelloCli.IsChecked == true)
            {
                _currentConfig.SelectedEngine = EngineType.FontelloCli;
            }
            else if (rbSvg2Ttf.IsChecked == true)
            {
                _currentConfig.SelectedEngine = EngineType.Svg2Ttf;
            }
            
            UpdateEngineVisibility();
            UpdateEngineDescription();
        }
        
        /// <summary>
        /// 更新引擎面板可见性
        /// </summary>
        private void UpdateEngineVisibility()
        {
            // 检查控件是否已初始化
            if (panelFontForge == null || panelFontelloCli == null)
                return;
                
            // 隐藏所有配置面板
            panelFontForge.Visibility = Visibility.Collapsed;
            panelFontelloCli.Visibility = Visibility.Collapsed;
            if (panelSvg2Ttf != null)
                panelSvg2Ttf.Visibility = Visibility.Collapsed;
            
            // 显示选中的配置面板
            if (rbFontForge.IsChecked == true)
            {
                panelFontForge.Visibility = Visibility.Visible;
            }
            else if (rbFontelloCli.IsChecked == true)
            {
                panelFontelloCli.Visibility = Visibility.Visible;
            }
            else if (rbSvg2Ttf.IsChecked == true && panelSvg2Ttf != null)
            {
                panelSvg2Ttf.Visibility = Visibility.Visible;
            }
        }
        
        /// <summary>
        /// 更新引擎描述
        /// </summary>
        private void UpdateEngineDescription()
        {
            // 检查控件是否已初始化
            if (txtEngineDescription == null)
                return;
                
            if (rbFontForge.IsChecked == true)
            {
                txtEngineDescription.Text = "FontForge是一个功能强大的字体编辑器，支持本地转换，无需网络连接。";
            }
            else if (rbFontelloCli.IsChecked == true)
            {
                txtEngineDescription.Text = "Fontello CLI是基于Fontello在线服务的命令行工具，需要网络连接和Node.js环境。";
            }
            else if (rbSvg2Ttf.IsChecked == true)
            {
                txtEngineDescription.Text = "SVG2TTF由Fontello团队维护，能把SVG格式图标转换成TTF字体文件，使图标在网页和数字媒体中像文本一样灵活高效渲染。";
            }
        }
        
        #region FontForge配置事件
        
        /// <summary>
        /// FontForge路径文本改变事件
        /// </summary>
        private void FontForgePath_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            UpdateFontForgeStatus();
        }
        
        /// <summary>
        /// 自动检测FontForge路径
        /// </summary>
        private void AutoDetectFontForge_Click(object sender, RoutedEventArgs e)
        {
            var detectedPath = _configService.AutoDetectFontForgePath();
            if (!string.IsNullOrEmpty(detectedPath))
            {
                txtFontForgePath.Text = detectedPath;
                MessageBox.Show($"已自动检测到FontForge路径：\n{detectedPath}", "自动检测成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("未能自动检测到FontForge安装路径。\n请手动选择FontForge的bin目录。", "自动检测失败", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        
        /// <summary>
        /// 浏览FontForge路径
        /// </summary>
        private void BrowseFontForge_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择FontForge的bin目录";
                dialog.SelectedPath = txtFontForgePath.Text;
                
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtFontForgePath.Text = dialog.SelectedPath;
                }
            }
        }
        
        /// <summary>
        /// 测试FontForge配置
        /// </summary>
        private void TestFontForge_Click(object sender, RoutedEventArgs e)
        {
            var config = new FontForgeConfig { InstallPath = txtFontForgePath.Text };
            var isValid = _configService.ValidateFontForgeConfig(config);
            
            if (isValid)
            {
                MessageBox.Show("FontForge配置测试成功！\n已找到ffpython.exe文件。", "测试成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("FontForge配置测试失败！\n请检查路径是否正确，确保bin目录中包含ffpython.exe文件。", "测试失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        /// <summary>
        /// 更新FontForge状态
        /// </summary>
        private void UpdateFontForgeStatus()
        {
            // 检查控件是否已初始化
            if (txtFontForgePath == null || lblFontForgeStatus == null)
                return;
                
            var config = new FontForgeConfig { InstallPath = txtFontForgePath.Text };
            var isValid = _configService.ValidateFontForgeConfig(config);
            
            if (isValid)
            {
                lblFontForgeStatus.Text = "状态：配置有效 ✓";
                lblFontForgeStatus.Foreground = new SolidColorBrush(Color.FromRgb(16, 185, 129)); // Green
            }
            else if (string.IsNullOrWhiteSpace(txtFontForgePath.Text))
            {
                lblFontForgeStatus.Text = "状态：未配置";
                lblFontForgeStatus.Foreground = new SolidColorBrush(Color.FromRgb(107, 114, 128)); // Gray
            }
            else
            {
                lblFontForgeStatus.Text = "状态：配置无效 ✗";
                lblFontForgeStatus.Foreground = new SolidColorBrush(Color.FromRgb(239, 68, 68)); // Red
            }
        }
        
        #endregion
        
        #region Fontello CLI配置事件
        
        /// <summary>
        /// Node.js路径文本改变事件
        /// </summary>
        private void NodeJsPath_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            UpdateFontelloCliStatus();
        }
        
        /// <summary>
        /// Fontello CLI路径文本改变事件
        /// </summary>
        private void FontelloCliPath_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            UpdateFontelloCliStatus();
        }
        
        /// <summary>
        /// 自动检测Node.js路径
        /// </summary>
        private void AutoDetectNodeJs_Click(object sender, RoutedEventArgs e)
        {
            var detectedPath = _configService.AutoDetectNodeJsPath();
            if (!string.IsNullOrEmpty(detectedPath))
            {
                txtNodeJsPath.Text = detectedPath;
                MessageBox.Show($"已自动检测到Node.js路径：\n{detectedPath}", "自动检测成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("未能自动检测到Node.js安装路径。\n请手动选择Node.js的安装目录。", "自动检测失败", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        
        /// <summary>
        /// 浏览Node.js路径
        /// </summary>
        private void BrowseNodeJs_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择Node.js安装目录";
                dialog.SelectedPath = txtNodeJsPath.Text;
                
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtNodeJsPath.Text = dialog.SelectedPath;
                }
            }
        }
        
        /// <summary>
        /// 浏览Fontello CLI项目路径
        /// </summary>
        private void BrowseFontelloCli_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择Fontello CLI项目目录";
                dialog.SelectedPath = txtFontelloCliPath.Text;
                
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtFontelloCliPath.Text = dialog.SelectedPath;
                }
            }
        }
        
        /// <summary>
        /// 测试Fontello CLI配置
        /// </summary>
        private void TestFontelloCli_Click(object sender, RoutedEventArgs e)
        {
            var config = new FontelloCliConfig 
            { 
                NodeJsPath = txtNodeJsPath.Text,
                FontelloCliPath = txtFontelloCliPath.Text,
                ServerUrl = txtServerUrl.Text
            };
            
            var isValid = _configService.ValidateFontelloCliConfig(config);
            
            if (isValid)
            {
                MessageBox.Show("Fontello CLI配置测试成功！\n所有必需的文件都已找到。", "测试成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("Fontello CLI配置测试失败！\n请检查：\n1. Node.js路径是否正确\n2. Fontello CLI项目路径是否正确\n3. 项目目录中是否包含package.json文件", "测试失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        /// <summary>
        /// 更新Fontello CLI状态
        /// </summary>
        private void UpdateFontelloCliStatus()
        {
            // 检查控件是否已初始化
            if (txtNodeJsPath == null || txtFontelloCliPath == null || txtServerUrl == null || lblFontelloCliStatus == null)
                return;
                
            var config = new FontelloCliConfig 
            { 
                NodeJsPath = txtNodeJsPath.Text,
                FontelloCliPath = txtFontelloCliPath.Text,
                ServerUrl = txtServerUrl.Text
            };
            
            var isValid = _configService.ValidateFontelloCliConfig(config);
            
            if (isValid)
            {
                lblFontelloCliStatus.Text = "状态：配置有效 ✓";
                lblFontelloCliStatus.Foreground = new SolidColorBrush(Color.FromRgb(16, 185, 129)); // Green
            }
            else if (string.IsNullOrWhiteSpace(txtNodeJsPath.Text) || string.IsNullOrWhiteSpace(txtFontelloCliPath.Text))
            {
                lblFontelloCliStatus.Text = "状态：未配置";
                lblFontelloCliStatus.Foreground = new SolidColorBrush(Color.FromRgb(107, 114, 128)); // Gray
            }
            else
            {
                lblFontelloCliStatus.Text = "状态：配置无效 ✗";
                lblFontelloCliStatus.Foreground = new SolidColorBrush(Color.FromRgb(239, 68, 68)); // Red
            }
        }
        
        #endregion
        
        #region 窗口按钮事件
        
        /// <summary>
        /// 保存配置
        /// </summary>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 更新配置对象
                if (rbFontForge.IsChecked == true)
                {
                    _currentConfig.SelectedEngine = EngineType.FontForge;
                }
                else if (rbFontelloCli.IsChecked == true)
                {
                    _currentConfig.SelectedEngine = EngineType.FontelloCli;
                }
                else if (rbSvg2Ttf.IsChecked == true)
                {
                    _currentConfig.SelectedEngine = EngineType.Svg2Ttf;
                }
                
                // 更新FontForge配置
                _currentConfig.FontForge.InstallPath = txtFontForgePath.Text;
                _currentConfig.FontForge.IsValidated = _configService.ValidateFontForgeConfig(_currentConfig.FontForge);
                
                // 更新Fontello CLI配置
                _currentConfig.FontelloCli.NodeJsPath = txtNodeJsPath.Text;
                _currentConfig.FontelloCli.FontelloCliPath = txtFontelloCliPath.Text;
                _currentConfig.FontelloCli.ServerUrl = txtServerUrl.Text;
                _currentConfig.FontelloCli.IsValidated = _configService.ValidateFontelloCliConfig(_currentConfig.FontelloCli);
                
                // 更新SVG2TTF配置
                _currentConfig.Svg2Ttf.NodeJsPath = txtSvg2TtfNodeJsPath.Text;
                _currentConfig.Svg2Ttf.IsValidated = _configService.ValidateSvg2TtfConfig(_currentConfig.Svg2Ttf);
                
                // 验证当前选择的引擎配置是否有效
                bool isCurrentEngineValid = false;
                if (_currentConfig.SelectedEngine == EngineType.FontForge)
                {
                    isCurrentEngineValid = _currentConfig.FontForge.IsValidated;
                }
                else if (_currentConfig.SelectedEngine == EngineType.FontelloCli)
                {
                    isCurrentEngineValid = _currentConfig.FontelloCli.IsValidated;
                }
                else if (_currentConfig.SelectedEngine == EngineType.Svg2Ttf)
                {
                    isCurrentEngineValid = _currentConfig.Svg2Ttf.IsValidated;
                }
                
                if (!isCurrentEngineValid)
                {
                    var result = MessageBox.Show(
                        "当前选择的引擎配置无效，是否仍要保存？\n\n" +
                        "建议先修复配置问题再保存，否则主程序可能无法正常工作。",
                        "配置验证警告",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Warning);
                        
                    if (result == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                
                // 保存配置
                if (_configService.SaveConfig(_currentConfig))
                {
                    MessageBox.Show("配置保存成功！", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    DialogResult = true;
                    Close();
                }
                else
                {
                    MessageBox.Show("配置保存失败！请检查文件权限。", "保存失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置时发生错误：\n{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        /// <summary>
        /// 取消配置
        /// </summary>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
        
        #endregion
        
        #region 复制命令事件
        
        /// <summary>
        /// 复制FontForge安装命令
        /// </summary>
        private void CopyFontForgeCmd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtFontForgeInstallCmd != null)
                {
                    System.Windows.Clipboard.SetText(txtFontForgeInstallCmd.Text);
                    MessageBox.Show("安装命令已复制到剪贴板！", "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        /// <summary>
        /// 复制Node.js安装命令
        /// </summary>
        private void CopyNodeJsCmd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtNodeJsInstallCmd != null)
                {
                    System.Windows.Clipboard.SetText(txtNodeJsInstallCmd.Text);
                    MessageBox.Show("Node.js安装命令已复制到剪贴板！", "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        /// <summary>
        /// 复制Fontello CLI安装命令
        /// </summary>
        private void CopyFontelloCliCmd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtFontelloCliInstallCmd != null)
                {
                    System.Windows.Clipboard.SetText(txtFontelloCliInstallCmd.Text);
                    MessageBox.Show("Fontello CLI安装命令已复制到剪贴板！", "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        #endregion
        
        #region SVG2TTF 配置事件
        
        /// <summary>
        /// SVG2TTF Node.js路径文本改变事件
        /// </summary>
        private void Svg2TtfNodeJsPath_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            UpdateSvg2TtfStatus();
        }
        
        /// <summary>
        /// 自动检测SVG2TTF Node.js路径
        /// </summary>
        private void AutoDetectSvg2TtfNodeJs_Click(object sender, RoutedEventArgs e)
        {
            var detectedPath = _configService.AutoDetectNodeJsPath();
            if (!string.IsNullOrEmpty(detectedPath))
            {
                txtSvg2TtfNodeJsPath.Text = detectedPath;
                MessageBox.Show($"已自动检测到Node.js路径：\n{detectedPath}", "自动检测成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("未能自动检测到Node.js安装路径。\n请手动选择Node.js的安装目录。", "自动检测失败", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        
        /// <summary>
        /// 浏览SVG2TTF Node.js路径
        /// </summary>
        private void BrowseSvg2TtfNodeJs_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.Description = "选择Node.js安装目录";
                dialog.SelectedPath = txtSvg2TtfNodeJsPath.Text;
                
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtSvg2TtfNodeJsPath.Text = dialog.SelectedPath;
                }
            }
        }
        
        /// <summary>
        /// 测试SVG2TTF配置
        /// </summary>
        private void TestSvg2Ttf_Click(object sender, RoutedEventArgs e)
        {
            var config = new Svg2TtfConfig 
            { 
                NodeJsPath = txtSvg2TtfNodeJsPath.Text
            };
            
            var isValid = _configService.ValidateSvg2TtfConfig(config);
            
            if (isValid)
            {
                MessageBox.Show("SVG2TTF配置测试成功！\n已找到Node.js和svg2ttf包。", "测试成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("SVG2TTF配置测试失败！\n请检查：\n1. Node.js路径是否正确\n2. 是否已安装svg2ttf包 (npm install -g svg2ttf)", "测试失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        /// <summary>
        /// 更新SVG2TTF状态
        /// </summary>
        private void UpdateSvg2TtfStatus()
        {
            // 检查控件是否已初始化
            if (txtSvg2TtfNodeJsPath == null || lblSvg2TtfStatus == null)
                return;
                
            var config = new Svg2TtfConfig 
            { 
                NodeJsPath = txtSvg2TtfNodeJsPath.Text
            };
            
            var isValid = _configService.ValidateSvg2TtfConfig(config);
            
            if (isValid)
            {
                lblSvg2TtfStatus.Text = "状态：配置有效 ✓";
                lblSvg2TtfStatus.Foreground = new SolidColorBrush(Color.FromRgb(16, 185, 129)); // Green
            }
            else if (string.IsNullOrWhiteSpace(txtSvg2TtfNodeJsPath.Text))
            {
                lblSvg2TtfStatus.Text = "状态：未配置";
                lblSvg2TtfStatus.Foreground = new SolidColorBrush(Color.FromRgb(107, 114, 128)); // Gray
            }
            else
            {
                lblSvg2TtfStatus.Text = "状态：配置无效 ✗";
                lblSvg2TtfStatus.Foreground = new SolidColorBrush(Color.FromRgb(239, 68, 68)); // Red
            }
        }
        
        /// <summary>
        /// 复制SVG2TTF Node.js安装命令
        /// </summary>
        private void CopySvg2TtfNodeJsCmd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtSvg2TtfNodeJsInstallCmd != null)
                {
                    System.Windows.Clipboard.SetText(txtSvg2TtfNodeJsInstallCmd.Text);
                    MessageBox.Show("Node.js安装命令已复制到剪贴板！", "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        /// <summary>
        /// 复制SVG2TTF安装命令
        /// </summary>
        private void CopySvg2TtfCmd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtSvg2TtfInstallCmd != null)
                {
                    System.Windows.Clipboard.SetText(txtSvg2TtfInstallCmd.Text);
                    MessageBox.Show("SVG2TTF安装命令已复制到剪贴板！", "复制成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        #endregion
    }
}